package com.example.uupaymuch.controller.channel.wudipay;

import com.example.uupaymuch.controller.notice.wudi.RefundComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class RefundController {

    @Autowired
    private RefundComponent refundUtil;
    private final Random random = new Random();
    private final double successProbability = 1; // 50% 的成功概率

    @PostMapping("/charges/{chargeId}/refund")
    public ResponseEntity<Map<String, Object>> createTransaction(@RequestBody Map<String, Object> request) {
        // 生成一个随机数，并与成功概率进行比较
        boolean isSuccess = random.nextDouble() < successProbability;
        Map<String, Object> response = new HashMap<>();
        // 模拟入参
        String txid = request.get("txid") != null ? (String) request.get("txid") : "";
        String amount = request.get("amount") != null ? request.get("amount").toString() : "";
        String correlation_id = request.get("debtor_name") != null ? (String) request.get("debtor_name") : "";

        ZonedDateTime now = ZonedDateTime.now();
        String formattedTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"));
        response.put("uuid", UUID.randomUUID().toString());
        response.put("amount", amount);
        response.put("status", "CREATE");
        response.put("provider", "FAKE_BANK");
        response.put("charge_id", 129992);
        response.put("correlation_id", correlation_id);
        response.put("workspace_id", 34);
        response.put("reason", null);
        response.put("account_id", 1);
        response.put("updated_at", "2023-12-15T19:49:20.000000Z");
        response.put("created_at", "2023-12-15T19:49:20.000000Z");
        response.put("id", 110);
        if (isSuccess) {

            // 回调
            refundUtil.doNotifyRefund(txid, amount);
            return ResponseEntity.ok(response);
        } else {

            // 回调
            refundUtil.doNotifyRefund(txid, amount);
            return ResponseEntity.status(500).body(response);
        }
    }

}